package util;

import com.xyy.util.StringUtil;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * aes加密/解密
 *
 * @author dake
 * @date 20200330
 */
public class AESUtil {

    public static void main(String[] args) throws Exception {
        String sercetKey = "c9d40faceff82565386d648158c3f1eb";
        String decrypt = decrypt("TABMJzdf/kC597D9TDslslf4qmwHfPwmmV+uSw/kB0c=", sercetKey);
        System.out.println(decrypt);
    }

    private static final String AES_CBC_PCK_ALG = "AES/CBC/PKCS5Padding";
    private static final byte[] AES_IV = initIv("AES/CBC/PKCS5Padding");
    private static final String CHARSET = "utf-8";

    private AESUtil() {
    }


    public static String encrypt(String content, String aesKey) throws Exception {
        if (StringUtil.isEmpty(content, aesKey)) {
            throw new Exception("加密失败, content: " + content + " ,密钥: " + aesKey);
        }
        Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);
        IvParameterSpec iv = new IvParameterSpec(AES_IV);
        cipher.init(1, new SecretKeySpec(Base64.getDecoder().decode(aesKey.getBytes(

        )), "AES"), iv);
        byte[] encryptBytes = cipher.doFinal(content.getBytes(CHARSET));
        return new String(Base64.getEncoder().encode(encryptBytes));
    }

    public static String decrypt(String content, String key) throws Exception {
        if (StringUtil.isEmpty(content, key)) {
            throw new Exception("解密失败, content: " + content + " ,密钥: " + key);
        }
        Cipher cipher = Cipher.getInstance(AES_CBC_PCK_ALG);
        IvParameterSpec iv = new IvParameterSpec(initIv(AES_CBC_PCK_ALG));
        cipher.init(2, new SecretKeySpec(Base64.getDecoder().decode(key.getBytes()), "AES"), iv);
        byte[] cleanBytes = cipher.doFinal(Base64.getDecoder().decode(content.getBytes()));
        return new String(cleanBytes, CHARSET);
    }

    private static byte[] initIv(String fullAlg) {
        byte[] iv;
        int i;
        try {
            Cipher cipher = Cipher.getInstance(fullAlg);
            int blockSize = cipher.getBlockSize();
            iv = new byte[blockSize];

            for (i = 0; i < blockSize; ++i) {
                iv[i] = 0;
            }

            return iv;
        } catch (Exception var5) {
            int blockSize = 16;
            iv = new byte[blockSize];

            for (i = 0; i < blockSize; ++i) {
                iv[i] = 0;
            }

            return iv;
        }
    }

}
